package com.easyfun.healthmagicbox;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseIntArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemLongClickListener;

import com.easyfun.healthmagicbox.base.BaseActivity;
import com.easyfun.healthmagicbox.base.DatabaseAccess;
import com.easyfun.healthmagicbox.base.DatabaseAccessImplementation;
import com.easyfun.healthmagicbox.comm.HealthInputDataDeleteTask;
import com.easyfun.healthmagicbox.comm.HealthThreadPool;
import com.easyfun.healthmagicbox.comm.TopHealthRequestTask;
import com.easyfun.healthmagicbox.ormlite.DatabaseHelper;
import com.easyfun.healthmagicbox.ormlite.ServerResponseCode;
import com.easyfun.healthmagicbox.pojo.ConstantData;
import com.easyfun.healthmagicbox.pojo.HealthInputData;
import com.easyfun.healthmagicbox.pojo.TopHealth;
import com.easyfun.healthmagicbox.sync.BasicCommCallback;
import com.easyfun.healthmagicbox.sync.CommCallback;
import com.easyfun.healthmagicbox.widget.DialogBuilder;
import com.easyfun.healthmagicbox.widget.DialogBuilder.OnDialogButtonClickListener;
import com.j256.ormlite.dao.Dao;

public class InputsCatagoryActivity extends BaseActivity implements
DatabaseAccess {
	private static final String LOG_TAG = InputsCatagoryActivity.class.getSimpleName();
	private ListView listLastActs;
	private ArrayAdapter<String> mInputAdapter;
	TextView txt_nationDesc = null;
	TextView txt_boxDesc = null;
	SparseIntArray inputlistIDs = new SparseIntArray();
	private String mInputtype; 

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.oneinputscatagory);
		if (!checkPersonId())
			return;
		super.addbackButton(this);
		mInputtype = getIntent().getStringExtra(ConstantData.INPUT_TYPE);
		listLastActs = (ListView) findViewById(R.id.catagorylistview);
		txt_nationDesc = (TextView) findViewById(R.id.graph_txtInNationContent);
		txt_boxDesc = (TextView) findViewById(R.id.graph_txtInboxContent);
		
		mInputAdapter = new ArrayAdapter<String>(this,
				R.layout.common_list_item_without_indicator,
				R.id.item_text,
				new ArrayList<String>());
		
		/*mInputAdapter = new CustomListItemAdaptor(this,
				R.layout.one_lastinputlistitem,
				new ArrayList<String>(), false);*/
		getLastInputActs(mInputAdapter);
	
		mInputAdapter.setNotifyOnChange(true);
		listLastActs.setAdapter(mInputAdapter);
	
		listLastActs.setOnItemLongClickListener(new OnItemLongClickListener() {
	
			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				final Integer inputid = inputlistIDs.get(position);
				new DialogBuilder(InputsCatagoryActivity.this)
					.setTitle("是否删除")
					.setMessage(mInputAdapter.getItem(position).toString())
					.setButtons("确定", "取消", new OnDialogButtonClickListener() {
						
						@Override
						public void onDialogButtonClick(Context context, DialogBuilder builder,
								Dialog dialog, int dialogId, int which) {
							if (which == BUTTON_LEFT)
							{
								try {
									Dao<HealthInputData, Integer> inputdao = getHelper(InputsCatagoryActivity.this).getInputDataDao();
									HealthInputData hid = inputdao.queryForId(inputid);
									inputdao.deleteById(inputid);
									getLastInputActs(mInputAdapter);					
									mInputAdapter.notifyDataSetChanged();
									HealthInputDataDeleteTask task = new
											HealthInputDataDeleteTask(hid.getSyncid().toString(),
													InputsCatagoryActivity.this,
													new BasicCommCallback());
									HealthThreadPool.getInstance().execute(task);
								} catch (SQLException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
							else
							{
								dialog.dismiss();
							}
						}
					}).create().show();;
				
				return true;
			}
		});
		Button one_cata_button = (Button) findViewById(R.id.one_cata_button);
		
		one_cata_button.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
				
			}
		});
	}

	private void getLastInputActs(ArrayAdapter<String> inputAdapter) {
		inputAdapter.clear();
		int i = 0;
		// get our dao
		try {
			Dao<HealthInputData, Integer> inputDao = getHelper(this)
					.getInputDataDao();
			List<HealthInputData> pps = inputDao.queryBuilder()
					.orderBy("valueTime", false).where()
					.eq("personID", getPersonid())
					.and()
					.eq("valueType", mInputtype).query();
			// List<HealthInputData> pps = inputDao.queryForEq("personid",
			// getPersonid());

			for (HealthInputData input : pps) {
				SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm");
				// 前面的lSysTime是秒数，先乘1000得到毫秒数，再转为java.util.Date类型
				java.util.Date dt = new Date(Long.valueOf(input.getValueTime())
						.longValue());
				String time = sdf.format(dt); // 得到精确到秒的表示：08/31/2006 21:08:00

				// String time = String.format(Locale.CHINA,"%tm-%td %tH:%tM",
				// );
				String value = String.format(
						ConstantData.IdToNameMapping.get(input.getValueType()),
						input.getValueData());
				inputAdapter.add(time + " " + value);
				inputlistIDs.put(i, Integer.valueOf(input.getId()));
				i++;
				if (i > 50) {
					break;
				}
			}
			Log.i(LOG_TAG, "get last input data.");

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (i == 0)
		{
			inputAdapter.add("没有数据，请输入");
		}
		else
		{
			showTop();
		}
		return;
	}

	protected void showTop() {
		try {
			Dao<HealthInputData, Integer> inputDataDao = getHelper(this)
					.getInputDataDao();

			
					List<HealthInputData> hids = inputDataDao.queryBuilder()
							.orderBy("valueTime", false).where()
							.eq("personID", m_personid).and()
							.eq("valueType", mInputtype).query();
					if (hids.size() < 1)
						return;
					HealthInputData hid = hids.get(0);
					CommCallback ccb = new BasicCommCallback();
					TopHealthRequestTask task = new TopHealthRequestTask(
							m_personid, this, ccb, hid.getValueData(),
							mInputtype.toString());
					HealthThreadPool.getInstance().execute(task);
					String responseValue = "";
					int i = 0;
					ServerResponseCode src = ccb.getCommResult(
							TopHealthRequestTask.class, responseValue);
					while ((src == ServerResponseCode.WAITING) && (i < 50)) {
						synchronized (ccb) {
							try {
								ccb.wait(100);
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
						src = ccb.getCommResult(
								TopHealthRequestTask.class, responseValue);
						i++;
					}

					if (src != ServerResponseCode.SUCCESS) {
						Toast.makeText(this, "Get Top failed.",
								Toast.LENGTH_SHORT).show();
					}
					Dao<TopHealth, Integer> topDao = getHelper(this)
							.getTopDao();

					List<TopHealth> tops = topDao.queryBuilder()
							.orderBy("id", false).where()
							.eq("personID", m_personid).and()
							.eq("valueType", mInputtype).query();
					if (tops.size() < 1) {
						txt_boxDesc.setText("没能取得数据 (:<");

						txt_nationDesc.setText("没能取得数据 (:<");
						return;
					}
					TopHealth top = tops.get(0);
					txt_boxDesc.setText(top.getTopNumberInBox()
							+ top.getTopResult());

					txt_nationDesc.setText(top.getTopNumberInNation()
							+ top.getTopInfo());


		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	
	@Override
	public DatabaseHelper getHelper(Context context) {
		// TODO Auto-generated method stub
		return DatabaseAccessImplementation.getInstance().getHelper(context);
	}
}
